import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:get/get.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:signature/signature.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../../../common/api/index.dart';
import '../../../common/models/index.dart';
import '../../../common/models/project/project_rule_model.dart';
import '../../../common/services/user_service.dart';
import '../../../common/services/dio_service.dart';
import '../../../common/utils/index.dart';
import '../../../common/mixins/user_profile_mixin.dart';

class CaigouAssessmentDetialController extends GetxController with UserProfileMixin {
  CaigouAssessmentDetialController();

  // 🔥 状态管理
  final isLoading = true.obs;
  final errorMessage = ''.obs;
  final Rx<ProjectModel?> project = Rx<ProjectModel?>(null);
  
  // 🏢 供应商列表状态管理
  final isLoadingSuppliers = false.obs;
  final supplierErrorMessage = ''.obs;
  final RxList<ProjectSupplier> projectSuppliers = <ProjectSupplier>[].obs;
  
  // 👥 评标专家列表状态管理
  final isLoadingExperts = false.obs;
  final expertErrorMessage = ''.obs;
  final RxList<ProjectExpert> projectExperts = <ProjectExpert>[].obs;
  
  // 📋 项目评审规则状态管理
  final isLoadingRules = false.obs;
  final ruleErrorMessage = ''.obs;
  final Rx<ProjectRuleModel?> projectRules = Rx<ProjectRuleModel?>(null);
  final showRulesBottomSheet = false.obs;
  
  // 🏢 选中的供应商状态管理
  final Rx<ProjectSupplier?> selectedSupplier = Rx<ProjectSupplier?>(null);
  final showSupplierBidSheet = false.obs;
  
  // 📁 供应商文件列表状态管理
  final isLoadingSupplierFiles = false.obs;
  final supplierFilesErrorMessage = ''.obs;
  final RxList<SupplierFileModel> supplierFiles = <SupplierFileModel>[].obs;
  
  // 📄 招标文件列表状态管理
  final isLoadingBidFiles = false.obs;
  final bidFilesErrorMessage = ''.obs;
  final RxList<SupplierFileModel> bidFiles = <SupplierFileModel>[].obs;
  
  // 📥 文件下载状态管理
  final RxMap<int, double> downloadProgress = <int, double>{}.obs; // 文件ID -> 下载进度(0-1)
  final RxMap<int, bool> isDownloading = <int, bool>{}.obs; // 文件ID -> 是否正在下载
  
  // 👨‍💼 评标状态管理
  final isTeamLeader = false.obs; // 是否为组长
  final bidOpinion = ''.obs; // 评标意见（仅组长需要）
  final isCheckingLastExpert = false.obs; // 是否正在检查最后专家
  
  // 🎯 评分数据管理
  final Map<String, TextEditingController> scoreControllers = {};
  final scoreSubmitted = false.obs; // 评分是否已提交
  
  // 🖊️ 手写签名管理
  late SignatureController signatureController;
  final hasSignature = false.obs; // 是否已有签名
  final signatureUploaded = false.obs; // 签名是否已上传
  final isUploading = false.obs; // 正在上传状态
  final uploadErrorMessage = ''.obs; // 上传错误信息
  
  // 项目ID
  int? projectId;

  // 🔥 获取当前登录专家的ID（从UserProfileMixin）
  int get currentExpertId {
    final expertIdStr = expertId;
    final parsedId = int.tryParse(expertIdStr);
    
    if (parsedId == null || parsedId <= 0) {
      debugPrint('⚠️ 专家ID无效: $expertIdStr，使用默认值1');
      return 1;
    }
    
    debugPrint('✅ 使用专家ID: $parsedId');
    return parsedId;
  }

  _initData() {
    _initializeParameters();
    _initializeData(); // 在参数初始化后再初始化数据
    _initializeSignature(); // 初始化签名控制器
    update(["caigou_assessment_detial"]);
  }
  
  /// 初始化签名控制器
  void _initializeSignature() {
    signatureController = SignatureController(
      penStrokeWidth: 2,
      penColor: Colors.black,
      exportBackgroundColor: Colors.white,
    );
    
    // 监听签名变化
    signatureController.addListener(() {
      hasSignature.value = signatureController.isNotEmpty;
    });
  }

  /// 统一的参数初始化方法
  void _initializeParameters() {
    try {
      final args = Get.arguments;
      
      if (args != null && args is Map<String, dynamic>) {
        projectId = args['projectId'] is int ? args['projectId'] as int : 
                   int.tryParse(args['projectId']?.toString() ?? '0');
        
        debugPrint('📋 采购评估详情页 - 参数初始化成功: projectId=$projectId');
      } else {
        _setDefaultParameters();
      }
    } catch (e) {
      debugPrint('❌ 采购评估详情页 - 参数初始化失败: $e');
      _setDefaultParameters();
    }
  }

  /// 设置默认参数
  void _setDefaultParameters() {
    projectId = null;
    debugPrint('⚠️ 采购评估详情页 - 使用默认参数');
  }

  /// 在参数初始化后进行数据初始化
  void _initializeData() {
    if (projectId != null && projectId! > 0) {
      loadProjectDetail();
      loadProjectSuppliers();
      // loadProjectExperts(); // 暂不加载评标专家列表
    } else {
      errorMessage.value = projectId == null ? '未找到项目ID' : '项目ID无效';
      isLoading.value = false;
      debugPrint('❌ 采购评估详情页 - 项目ID无效，无法加载数据');
    }
  }

  /// 加载项目详细信息
  Future<void> loadProjectDetail() async {
    if (projectId == null) return;
    
    try {
      debugPrint('🔄 采购评估详情页 - 开始加载项目详细信息');
      isLoading.value = true;
      errorMessage.value = '';
      
      final projectDetail = await ProjectApi.getProjectInfo(projectId: projectId!);
      project.value = projectDetail;
      
      debugPrint('✅ 采购评估详情页 - 加载项目详细信息成功');
      debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      debugPrint('📋 项目详细信息：');
      debugPrint('  ├─ 项目ID: ${projectDetail.id}');
      debugPrint('  ├─ 项目名称: ${projectDetail.projectName ?? "未命名"}');
      debugPrint('  ├─ 项目编号: ${projectDetail.projectNo ?? "无"}');
      debugPrint('  ├─ 申报部门: ${projectDetail.declareDepartment ?? "无"}');
      debugPrint('  ├─ 预算金额: ${projectDetail.budgetAmount ?? "无"}万元');
      debugPrint('  ├─ 项目类型: ${projectDetail.type}');
      debugPrint('  ├─ 项目管理员: ${projectDetail.projectManager ?? "无"}');
      debugPrint('  ├─ 项目联系人: ${projectDetail.projectContact ?? "无"}');
      debugPrint('  ├─ 联系电话: ${projectDetail.phone ?? "无"}');
      debugPrint('  ├─ 申报时间: ${projectDetail.declareTime ?? "无"}');
      debugPrint('  ├─ 项目当前状态: ${projectDetail.status} (${ProjectModel.getStatusTextByValue(projectDetail.status)})');
      debugPrint('  ├─ 评标时间: ${projectDetail.bidTime ?? "无"}');
      debugPrint('  ├─ 投标开始时间: ${projectDetail.signupBeginTime ?? "无"}');
      debugPrint('  ├─ 投标结束时间: ${projectDetail.signupEndTime ?? "无"}');
      debugPrint('  ├─ 建设部门: ${projectDetail.buildDepartment ?? "无"}');
      debugPrint('  ├─ 采购方式: ${projectDetail.procurementMethod ?? "无"}');
      debugPrint('  ├─ 投标标志: ${projectDetail.bidFlag ?? "无"}');
      debugPrint('  └─ 投标价格: ${projectDetail.bidPrice ?? "无"}');
      debugPrint('');
      debugPrint('📝 项目描述信息：');
      debugPrint('  ├─ 项目背景: ${projectDetail.background?.isNotEmpty == true ? projectDetail.background!.substring(0, projectDetail.background!.length > 50 ? 50 : projectDetail.background!.length) + "..." : "无"}');
      debugPrint('  ├─ 项目要求: ${projectDetail.requirements?.isNotEmpty == true ? projectDetail.requirements!.substring(0, projectDetail.requirements!.length > 50 ? 50 : projectDetail.requirements!.length) + "..." : "无"}');
      debugPrint('  ├─ 项目目标: ${projectDetail.objectives?.isNotEmpty == true ? projectDetail.objectives!.substring(0, projectDetail.objectives!.length > 50 ? 50 : projectDetail.objectives!.length) + "..." : "无"}');
      debugPrint('  ├─ 项目计划: ${projectDetail.plan?.isNotEmpty == true ? projectDetail.plan!.substring(0, projectDetail.plan!.length > 50 ? 50 : projectDetail.plan!.length) + "..." : "无"}');
      debugPrint('  └─ 项目实施: ${projectDetail.implementation?.isNotEmpty == true ? projectDetail.implementation!.substring(0, projectDetail.implementation!.length > 50 ? 50 : projectDetail.implementation!.length) + "..." : "无"}');
      debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      debugPrint('');
      
    } catch (e) {
      debugPrint('❌ 采购评估详情页 - 加载项目详细信息失败: $e');
      errorMessage.value = e.toString().replaceAll('Exception: ', '');
    } finally {
      isLoading.value = false;
    }
  }

  /// 加载项目供应商列表
  Future<void> loadProjectSuppliers() async {
    if (projectId == null) return;
    
    try {
      debugPrint('🏢 采购评估详情页 - 开始加载项目供应商列表');
      isLoadingSuppliers.value = true;
      supplierErrorMessage.value = '';
      
      // 获取当前登录的专家ID
      final expertInfo = UserService.to.currentExpertInfo;
      if (expertInfo == null || expertInfo.id == null || expertInfo.id == 0) {
        throw Exception('无法获取当前登录专家信息');
      }
      
      // 获取项目供应商列表
      final suppliers = await ProjectApi.getProjectSupplierList(
        projectId: projectId!,
        expertId: expertInfo.id!,
      );
      
      projectSuppliers.value = suppliers;
      debugPrint('✅ 采购评估详情页 - 加载项目供应商列表成功，共 ${suppliers.length} 个供应商');
      
      // 🔥🔥🔥 评标状态判断说明 🔥🔥🔥
      debugPrint('');
      debugPrint('🎯🎯🎯 评标状态判断规则说明 🎯🎯🎯');
      debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      debugPrint('📌 状态字段：supplier.bidFlag');
      debugPrint('📌 供应商ID字段：supplier.supplierId');
      debugPrint('📌 判断逻辑：');
      debugPrint('   ✅ bidFlag == 1  →  显示"已评标"（绿色标签）');
      debugPrint('   ⏳ bidFlag == 0  →  显示"待评标"（橙色标签）');
      debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      debugPrint('');
      
      // 格式化打印供应商列表
      if (suppliers.isNotEmpty) {
        debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        debugPrint('🏢 供应商列表详情：');
        
        // 统计投标状态
        int bidCount = 0;
        int noBidCount = 0;
        
        for (var i = 0; i < suppliers.length; i++) {
          final supplier = suppliers[i];
          final isBid = supplier.bidFlag == 1;
          
          if (isBid) {
            bidCount++;
          } else {
            noBidCount++;
          }
          
          debugPrint('');
          debugPrint('  ${i + 1}. 供应商信息：');
          debugPrint('     ├─ 记录ID (id): ${supplier.id}');
          debugPrint('     ├─ 🏢 供应商ID (supplierId): ${supplier.supplierId ?? "无"}');
          debugPrint('     ├─ 企业名称: ${supplier.corpName ?? "未知"}');
          debugPrint('     ├─ 法人代表: ${supplier.legalPerson ?? "无"}');
          debugPrint('     ├─ 联系人: ${supplier.contacts ?? "无"}');
          debugPrint('     ├─ 联系电话: ${supplier.phone ?? "无"}');
          debugPrint('     ├─ 企业地址: ${supplier.corpAddress ?? "无"}');
          debugPrint('     🔥 评标状态字段详细：');
          debugPrint('        ├─ bidFlag 原始值: ${supplier.bidFlag}');
          debugPrint('        ├─ bidFlag 数据类型: ${supplier.bidFlag.runtimeType}');
          debugPrint('        ├─ 判断结果 (bidFlag == 1): $isBid');
          debugPrint('        └─ 显示状态: ${isBid ? "✅ 已评标（绿色）" : "⏳ 待评标（橙色）"}');
          debugPrint('     ├─ 员工总数: ${supplier.totalStaff ?? "无"}');
          debugPrint('     ├─ 评分: ${supplier.score ?? "无"}');
          debugPrint('     ├─ 创建时间: ${supplier.createTime ?? "无"}');
          debugPrint('     └─ 项目ID: ${supplier.projectId}');
        }
        
        debugPrint('');
        debugPrint('📊 评标状态统计：');
        debugPrint('   ✅ 已评标：$bidCount 个供应商');
        debugPrint('   ⏳ 待评标（未评标）：$noBidCount 个供应商');
        debugPrint('   📦 总计：${suppliers.length} 个供应商');
        debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        debugPrint('');
      }
      
    } catch (e) {
      debugPrint('❌ 采购评估详情页 - 加载项目供应商列表失败: $e');
      supplierErrorMessage.value = e.toString().replaceAll('Exception: ', '');
    } finally {
      isLoadingSuppliers.value = false;
    }
  }

  /// 加载项目评标专家列表
  Future<void> loadProjectExperts() async {
    if (projectId == null) return;
    
    try {
      debugPrint('👥 采购评估详情页 - 开始加载项目评标专家列表');
      isLoadingExperts.value = true;
      expertErrorMessage.value = '';
      
      // 采购评估页面显示评标人专家列表 (flag = 2)
      final experts = await ProjectApi.getProjectExpertList(
        projectId: projectId!,
        flag: 2, // 2-评标人专家列表
      );
      
      projectExperts.value = experts;
      debugPrint('✅ 采购评估详情页 - 加载项目评标专家列表成功，共 ${experts.length} 个专家');
      
      // 打印每个专家的详细信息
      if (experts.isNotEmpty) {
        debugPrint('📋 评标专家列表详情：');
        for (var i = 0; i < experts.length; i++) {
          final expert = experts[i];
          debugPrint('  ${i + 1}. 专家ID: ${expert.expertId}, 姓名: ${expert.expertName}');
          debugPrint('     reviewStatus: ${expert.reviewStatus}');
          
          // 特别标记当前登录专家
          if (expert.expertId == currentExpertId) {
            debugPrint('     👉 这是当前登录专家！');
          }
        }
      }
      
    } catch (e) {
      debugPrint('❌ 采购评估详情页 - 加载项目评标专家列表失败: $e');
      expertErrorMessage.value = e.toString().replaceAll('Exception: ', '');
    } finally {
      isLoadingExperts.value = false;
    }
  }

  /// 刷新项目详细信息
  Future<void> refreshProjectDetail() async {
    await Future.wait([
      loadProjectDetail(),
      loadProjectSuppliers(),
      // loadProjectExperts(), // 暂不加载评标专家列表
    ]);
  }

  /// 单独刷新供应商列表
  Future<void> refreshProjectSuppliers() async {
    await loadProjectSuppliers();
  }

  /// 单独刷新专家列表
  Future<void> refreshProjectExperts() async {
    await loadProjectExperts();
  }

  /// 加载项目评审规则
  Future<void> loadProjectReviewRules() async {
    if (projectId == null) return;
    
    try {
      debugPrint('📋 采购评估详情页 - 开始加载项目评审规则');
      isLoadingRules.value = true;
      ruleErrorMessage.value = '';
      
      // 获取项目评审规则
      final rules = await ProjectApi.getProjectReviewRule(
        projectId: projectId!,
      );
      
      projectRules.value = rules;
      debugPrint('✅ 采购评估详情页 - 加载项目评审规则成功');
      debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      debugPrint('📋 评审规则详细信息：');
      debugPrint('  ├─ 项目ID: $projectId');
      debugPrint('  ├─ 评分规则数据长度: ${rules.scoreRule?.length ?? 0} 字符');
      debugPrint('  └─ 资格评审规则数据长度: ${rules.reviewRule?.length ?? 0} 字符');
      debugPrint('');
      
      // 格式化打印评分规则
      if (rules.scoreRule?.isNotEmpty == true) {
        debugPrint('📊 评分规则 (Score Rule):');
        debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        try {
          // 尝试美化打印JSON
          final dynamic scoreRuleData = jsonDecode(rules.scoreRule!);
          final prettyScoreRule = JsonEncoder.withIndent('  ').convert(scoreRuleData);
          debugPrint(prettyScoreRule);
        } catch (e) {
          debugPrint('  原始数据（JSON解析失败）: ${rules.scoreRule}');
        }
        debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        debugPrint('');
      } else {
        debugPrint('📊 评分规则: 无');
        debugPrint('');
      }
      
      // 格式化打印资格评审规则
      if (rules.reviewRule?.isNotEmpty == true) {
        debugPrint('📝 资格评审规则 (Review Rule):');
        debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        // 资格评审规则通常是HTML格式，打印前50行
        final lines = rules.reviewRule!.split('\n');
        final displayLines = lines.take(50).toList();
        for (var i = 0; i < displayLines.length; i++) {
          debugPrint('  ${(i + 1).toString().padLeft(3)}: ${displayLines[i]}');
        }
        if (lines.length > 50) {
          debugPrint('  ... (省略 ${lines.length - 50} 行)');
        }
        debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        debugPrint('');
      } else {
        debugPrint('📝 资格评审规则: 无');
        debugPrint('');
      }
      
    } catch (e) {
      debugPrint('❌ 采购评估详情页 - 加载项目评审规则失败: $e');
      ruleErrorMessage.value = e.toString().replaceAll('Exception: ', '');
    } finally {
      isLoadingRules.value = false;
    }
  }

  /// 显示评审规则底部弹窗
  Future<void> showReviewRulesBottomSheet() async {
    // 如果没有规则数据，先加载
    if (projectRules.value == null) {
      await loadProjectReviewRules();
    }
    
    // 如果加载成功，显示弹窗
    if (projectRules.value != null && ruleErrorMessage.value.isEmpty) {
      showRulesBottomSheet.value = true;
    }
  }

  /// 隐藏评审规则底部弹窗
  void hideReviewRulesBottomSheet() {
    showRulesBottomSheet.value = false;
  }

  /// 刷新项目评审规则
  Future<void> refreshProjectReviewRules() async {
    await loadProjectReviewRules();
  }

  /// 加载供应商文件列表（投标文件）
  Future<void> loadSupplierFiles() async {
    if (projectId == null || selectedSupplier.value == null) return;
    
    try {
      debugPrint('📁 采购评估详情页 - 开始加载供应商投标文件列表');
      isLoadingSupplierFiles.value = true;
      supplierFilesErrorMessage.value = '';
      
      final supplierId = selectedSupplier.value!.supplierId ?? 0;
      
      // 获取供应商上传的投标文件（fileType = 1）
      final files = await ProjectApi.getProjectFiles(
        projectId: projectId!,
        supplierId: supplierId,
        fileType: 1, // 1-供应商上传投标文件
      );
      
      supplierFiles.value = files;
      debugPrint('✅ 采购评估详情页 - 加载供应商投标文件列表成功，共 ${files.length} 个文件');
      
    } catch (e) {
      debugPrint('❌ 采购评估详情页 - 加载供应商投标文件列表失败: $e');
      supplierFilesErrorMessage.value = e.toString().replaceAll('Exception: ', '');
    } finally {
      isLoadingSupplierFiles.value = false;
    }
  }
  
  /// 刷新供应商文件列表
  Future<void> refreshSupplierFiles() async {
    await loadSupplierFiles();
  }
  
  /// 加载招标文件列表
  Future<void> loadBidFiles() async {
    if (projectId == null) return;
    
    try {
      debugPrint('📄 采购评估详情页 - 开始加载招标文件列表');
      isLoadingBidFiles.value = true;
      bidFilesErrorMessage.value = '';
      
      // 获取项目的招标文件（fileType = 0，不需要supplierId）
      final files = await ProjectApi.getProjectFiles(
        projectId: projectId!,
        supplierId: 0, // 招标文件不需要供应商ID
        fileType: 0, // 0-招标文件
      );
      
      bidFiles.value = files;
      debugPrint('✅ 采购评估详情页 - 加载招标文件列表成功，共 ${files.length} 个文件');
      
    } catch (e) {
      debugPrint('❌ 采购评估详情页 - 加载招标文件列表失败: $e');
      bidFilesErrorMessage.value = e.toString().replaceAll('Exception: ', '');
    } finally {
      isLoadingBidFiles.value = false;
    }
  }
  
  /// 刷新招标文件列表
  Future<void> refreshBidFiles() async {
    await loadBidFiles();
  }
  
  /// 下载供应商文件
  Future<void> downloadSupplierFile(SupplierFileModel file) async {
    if (file.id == null) {
      LoadingUtil.error('文件ID无效');
      return;
    }
    
    final fileId = file.id!;
    
    // 检查是否已经在下载
    if (isDownloading[fileId] == true) {
      LoadingUtil.info('文件正在下载中，请稍候...');
      return;
    }
    
    try {
      debugPrint('📥 采购评估详情页 - 开始下载文件');
      debugPrint('  ├─ 文件ID: $fileId');
      debugPrint('  ├─ 文件名: ${file.fileName}');
      debugPrint('  ├─ 文件URL: ${file.filePath}');
      debugPrint('  └─ 文件大小: ${file.fileSizeReadable}');
      
      // 标记为正在下载
      isDownloading[fileId] = true;
      downloadProgress[fileId] = 0.0;
      
      // 获取下载目录
      Directory? downloadDir;
      if (Platform.isAndroid) {
        // Android: 使用外部存储的Download目录
        downloadDir = Directory('/storage/emulated/0/Download');
        if (!await downloadDir.exists()) {
          downloadDir = await getExternalStorageDirectory();
        }
      } else if (Platform.isIOS) {
        // iOS: 使用应用文档目录
        downloadDir = await getApplicationDocumentsDirectory();
      } else {
        // 其他平台: 使用应用文档目录
        downloadDir = await getApplicationDocumentsDirectory();
      }
      
      if (downloadDir == null) {
        throw Exception('无法获取下载目录');
      }
      
      // 确保下载目录存在
      if (!await downloadDir.exists()) {
        await downloadDir.create(recursive: true);
      }
      
      // 构建保存路径，如果文件已存在则添加后缀
      String fileName = file.fileName ?? 'download_${DateTime.now().millisecondsSinceEpoch}';
      String savePath = '${downloadDir.path}/$fileName';
      
      // 如果文件已存在，添加时间戳后缀
      if (await File(savePath).exists()) {
        final timestamp = DateTime.now().millisecondsSinceEpoch;
        final nameWithoutExt = fileName.contains('.') 
            ? fileName.substring(0, fileName.lastIndexOf('.'))
            : fileName;
        final ext = fileName.contains('.') 
            ? fileName.substring(fileName.lastIndexOf('.'))
            : '';
        fileName = '${nameWithoutExt}_$timestamp$ext';
        savePath = '${downloadDir.path}/$fileName';
      }
      
      debugPrint('💾 保存路径: $savePath');
      
      // 使用DioService下载文件
      final dioService = DioService.to;
      await dioService.downloadFile(
        file.filePath ?? '',
        savePath,
        onReceiveProgress: (received, total) {
          if (total > 0) {
            final progress = received / total;
            downloadProgress[fileId] = progress;
            debugPrint('📊 下载进度: ${(progress * 100).toStringAsFixed(1)}% ($received / $total bytes)');
          }
        },
      );
      
      debugPrint('✅ 文件下载成功: $savePath');
      
      // 下载完成
      downloadProgress[fileId] = 1.0;
      
      LoadingUtil.success('文件已保存到: $savePath');
      
    } catch (e) {
      debugPrint('❌ 采购评估详情页 - 下载文件失败: $e');
      
      // 清除下载进度
      downloadProgress.remove(fileId);
      
      LoadingUtil.error(e.toString().replaceAll('Exception: ', ''));
    } finally {
      // 移除下载状态
      isDownloading.remove(fileId);
    }
  }

  /// 显示供应商评标弹窗
  Future<void> showSupplierBidBottomSheet(ProjectSupplier supplier) async {
    selectedSupplier.value = supplier;
    
    // 🔥 检查该供应商是否已被当前专家评标
    if (supplier.bidFlag == 1) {
      debugPrint('⚠️ 该供应商已被当前专家评标，bidFlag=${supplier.bidFlag}');
      LoadingUtil.info('该供应商已评标，不能重复评标！\n请选择其他待评标的供应商');
      return;
    }
    
    // 重置评标状态
    _resetBidState();
    
    // 🔥 自动检测是否是最后一个专家（组长）
    _autoCheckLeaderStatus();
    
    // 如果没有规则数据，先加载
    if (projectRules.value == null) {
      await loadProjectReviewRules();
    }
    
    // 加载供应商文件列表
    await loadSupplierFiles();
    
    // 加载招标文件列表
    await loadBidFiles();
    
    // 如果加载成功，显示弹窗
    if (projectRules.value != null && ruleErrorMessage.value.isEmpty) {
      // 🔥 打印评分表表头信息
      _printScoreTableHeader();
      
      showSupplierBidSheet.value = true;
    }
  }
  
  /// 打印评分表表头信息
  void _printScoreTableHeader() {
    debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    debugPrint('📋 点击供应商评标 - 评分表表头信息');
    debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    debugPrint('');
    debugPrint('🏢 选中的供应商信息：');
    debugPrint('  ├─ 供应商ID (supplierId): ${selectedSupplier.value?.supplierId}');
    debugPrint('  ├─ 供应商名称 (corpName): ${selectedSupplier.value?.corpName}');
    debugPrint('  ├─ 法人代表: ${selectedSupplier.value?.legalPerson ?? "无"}');
    debugPrint('  └─ 联系电话: ${selectedSupplier.value?.phone ?? "无"}');
    debugPrint('');
    
    if (projectRules.value?.scoreRule?.isNotEmpty == true) {
      try {
        final List<dynamic> scoreRules = jsonDecode(projectRules.value!.scoreRule!);
        
        // 🔥 动态生成表头HTML（包含单位名称列）
        StringBuffer tableHeaderBuffer = StringBuffer();
        tableHeaderBuffer.write('<tr>\n');
        
        // 第一列：单位名称（供应商名称）
        tableHeaderBuffer.write('    <th style="text-align: center; font-weight: bold;">单位名称</th>\n');
        
        int totalScore = 0;
        int columnCount = 1; // 从1开始，已有单位名称列
        List<String> columnDetails = ['列1: 单位名称（供应商名称）']; // 用于详细打印
        
        // 动态生成评分项列
        for (var i = 0; i < scoreRules.length; i++) {
          final Map<String, dynamic> ruleMap = scoreRules[i] as Map<String, dynamic>;
          final String type = ruleMap['type'] ?? '';
          final String content = ruleMap['content'] ?? '';
          final String score = ruleMap['score'] ?? '';
          final List<dynamic> subItems = ruleMap['subItems'] ?? [];
          
          if (type == 'total') {
            // 记录总分
            totalScore = int.tryParse(score) ?? 0;
            continue;
          }
          
          // 如果有子项，为每个子项创建列
          if (subItems.isNotEmpty) {
            for (var j = 0; j < subItems.length; j++) {
              final Map<String, dynamic> subMap = subItems[j] as Map<String, dynamic>;
              final String subContent = subMap['content'] ?? '';
              final String subScore = subMap['score'] ?? '';
              
              columnCount++;
              tableHeaderBuffer.write('    <th style="text-align: center; font-weight: bold;">$subContent<br/>($subScore)</th>\n');
              columnDetails.add('列${columnCount}: $subContent ($subScore)');
            }
          } else {
            // 没有子项，为主项创建列
            columnCount++;
            tableHeaderBuffer.write('    <th style="text-align: center; font-weight: bold;">$content<br/>($score)</th>\n');
            columnDetails.add('列${columnCount}: $content ($score)');
          }
        }
        
        // 最后一列：总分
        columnCount++;
        tableHeaderBuffer.write('    <th style="text-align: center; font-weight: bold;">总分</th>\n');
        tableHeaderBuffer.write('</tr>');
        
        final String tableHeader = tableHeaderBuffer.toString();
        
        debugPrint('📊 动态生成的评分表表头 (Table Header):');
        debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        debugPrint(tableHeader);
        debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        debugPrint('');
        
        debugPrint('📝 表头列结构分析：');
        debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        debugPrint('总列数: $columnCount 列');
        for (var detail in columnDetails) {
          debugPrint(detail);
        }
        debugPrint('列$columnCount: 总分（固定列）');
        debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        debugPrint('');
        
        debugPrint('📝 评分规则结构详细分析：');
        debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        debugPrint('评分规则总数: ${scoreRules.length} 项');
        debugPrint('');
        
        int mainItemCount = 0;
        int subItemCount = 0;
        
        for (var i = 0; i < scoreRules.length; i++) {
          final Map<String, dynamic> ruleMap = scoreRules[i] as Map<String, dynamic>;
          final String type = ruleMap['type'] ?? '';
          final String criteria = ruleMap['criteria'] ?? '';
          final String content = ruleMap['content'] ?? '';
          final String standard = ruleMap['standard'] ?? '';
          final String score = ruleMap['score'] ?? '';
          final List<dynamic> subItems = ruleMap['subItems'] ?? [];
          
          if (type == 'total') {
            debugPrint('${i + 1}. 【总分行】');
            debugPrint('   └─ 满分: $score 分');
          } else {
            mainItemCount++;
            debugPrint('');
            debugPrint('${i + 1}. 【主评分项 #$mainItemCount】');
            debugPrint('   ├─ 评分项 (criteria): $criteria');
            debugPrint('   ├─ 评分内容 (content): $content');
            debugPrint('   ├─ 评分标准 (standard): ${standard.length > 100 ? standard.substring(0, 100) + "..." : standard}');
            debugPrint('   ├─ 满分 (score): $score');
            
            if (subItems.isNotEmpty) {
              debugPrint('   └─ 子项数量: ${subItems.length} 个');
              
              for (var j = 0; j < subItems.length; j++) {
                final Map<String, dynamic> subMap = subItems[j] as Map<String, dynamic>;
                final String subContent = subMap['content'] ?? '';
                final String subStandard = subMap['standard'] ?? '';
                final String subScore = subMap['score'] ?? '';
                
                subItemCount++;
                debugPrint('      ${j + 1}. 子项：');
                debugPrint('         ├─ 内容: $subContent');
                debugPrint('         ├─ 标准: ${subStandard.length > 80 ? subStandard.substring(0, 80) + "..." : subStandard}');
                debugPrint('         └─ 满分: $subScore');
              }
            } else {
              debugPrint('   └─ 子项数量: 0 个');
            }
          }
        }
        
        debugPrint('');
        debugPrint('📊 统计信息：');
        debugPrint('  ├─ 主评分项数量: $mainItemCount 项');
        debugPrint('  ├─ 子评分项数量: $subItemCount 项');
        debugPrint('  ├─ 总评分项数量: ${mainItemCount + subItemCount} 项');
        debugPrint('  └─ 总分: $totalScore 分');
        debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        debugPrint('');
        
      } catch (e) {
        debugPrint('❌ 解析评分规则失败: $e');
        debugPrint('原始评分规则数据: ${projectRules.value!.scoreRule}');
      }
    } else {
      debugPrint('⚠️ 未找到评分规则数据');
    }
    
    debugPrint('');
  }
  
  /// 重置评标状态
  void _resetBidState() {
    isTeamLeader.value = false;
    bidOpinion.value = '';
    scoreSubmitted.value = false;
    signatureController.clear();
    hasSignature.value = false;
    signatureUploaded.value = false;
    isUploading.value = false;
    uploadErrorMessage.value = '';
    isCheckingLastExpert.value = false;
    
    // 清除所有评分输入控制器
    for (var controller in scoreControllers.values) {
      controller.clear();
    }
    scoreControllers.clear();
  }
  
  /// 🔥 验证所有评分项是否都已填写
  /// 返回：{ 'isValid': bool, 'missingItems': List<String> }
  Map<String, dynamic> _validateAllScoresFilled() {
    final List<String> missingItems = [];
    bool isValid = true;
    
    try {
      if (projectRules.value?.scoreRule?.isNotEmpty != true) {
        debugPrint('⚠️ 没有评分规则配置');
        return {'isValid': false, 'missingItems': ['没有评分规则配置']};
      }
      
      final List<dynamic> scoreRules = jsonDecode(projectRules.value!.scoreRule!);
      
      // 遍历所有评分规则，检查是否都已填写
      for (var rule in scoreRules) {
        final Map<String, dynamic> ruleMap = rule as Map<String, dynamic>;
        final String type = ruleMap['type'] ?? '';
        final String criteria = ruleMap['criteria'] ?? '';
        final String content = ruleMap['content'] ?? '';
        final String score = ruleMap['score'] ?? '';
        final List<dynamic> subItems = ruleMap['subItems'] ?? [];
        
        // 跳过总分行
        if (type == 'total') continue;
        
        // 如果有子项，检查每个子项是否都已填写
        if (subItems.isNotEmpty) {
          for (var i = 0; i < subItems.length; i++) {
            final Map<String, dynamic> subMap = subItems[i] as Map<String, dynamic>;
            final String subContent = subMap['content'] ?? '';
            final String subScore = subMap['score'] ?? '';
            
            // 构建子项评分key
            final subScoreKey = 'sub_score_${content}_${subContent}_$i';
            
            // 检查是否已创建controller
            if (!scoreControllers.containsKey(subScoreKey)) {
              isValid = false;
              missingItems.add('${criteria.isNotEmpty ? "$criteria - " : ""}$content - $subContent');
              continue;
            }
            
            // 检查是否已填写
            final scoreValue = scoreControllers[subScoreKey]!.text.trim();
            if (scoreValue.isEmpty) {
              isValid = false;
              missingItems.add('${criteria.isNotEmpty ? "$criteria - " : ""}$content - $subContent');
            } else {
              // 验证分数格式
              final parsedScore = double.tryParse(scoreValue);
              if (parsedScore == null) {
                isValid = false;
                missingItems.add('${criteria.isNotEmpty ? "$criteria - " : ""}$content - $subContent (分数格式错误)');
              } else {
                // 验证分数范围（0到满分）
                final maxScore = double.tryParse(subScore) ?? 0;
                if (parsedScore < 0 || parsedScore > maxScore) {
                  isValid = false;
                  missingItems.add('${criteria.isNotEmpty ? "$criteria - " : ""}$content - $subContent (分数必须在0-$maxScore之间)');
                }
              }
            }
          }
        } else {
          // 没有子项，检查主项是否已填写
          final scoreKey = 'score_${content}_${criteria}';
          
          // 检查是否已创建controller
          if (!scoreControllers.containsKey(scoreKey)) {
            isValid = false;
            missingItems.add('${criteria.isNotEmpty ? "$criteria - " : ""}$content');
            continue;
          }
          
          // 检查是否已填写
          final scoreValue = scoreControllers[scoreKey]!.text.trim();
          if (scoreValue.isEmpty) {
            isValid = false;
            missingItems.add('${criteria.isNotEmpty ? "$criteria - " : ""}$content');
          } else {
            // 验证分数格式
            final parsedScore = double.tryParse(scoreValue);
            if (parsedScore == null) {
              isValid = false;
              missingItems.add('${criteria.isNotEmpty ? "$criteria - " : ""}$content (分数格式错误)');
            } else {
              // 验证分数范围（0到满分）
              final maxScore = double.tryParse(score) ?? 0;
              if (parsedScore < 0 || parsedScore > maxScore) {
                isValid = false;
                missingItems.add('${criteria.isNotEmpty ? "$criteria - " : ""}$content (分数必须在0-$maxScore之间)');
              }
            }
          }
        }
      }
      
      debugPrint('📊 评分验证统计：');
      debugPrint('  ├─ 验证结果: ${isValid ? "✅ 通过" : "❌ 失败"}');
      debugPrint('  ├─ 未填写或错误项数: ${missingItems.length}');
      if (missingItems.isNotEmpty) {
        debugPrint('  └─ 详细列表:');
        for (var item in missingItems) {
          debugPrint('     • $item');
        }
      }
      
    } catch (e) {
      debugPrint('❌ 评分验证异常: $e');
      return {
        'isValid': false,
        'missingItems': ['验证过程出错：$e']
      };
    }
    
    return {
      'isValid': isValid,
      'missingItems': missingItems,
    };
  }
  
  /// 自动检测组长状态（静默检测，不显示toast）
  /// 在打开评标弹出框时自动调用
  Future<void> _autoCheckLeaderStatus() async {
    if (projectId == null || selectedSupplier.value == null) return;
    
    try {
      isCheckingLastExpert.value = true;
      
      debugPrint('🔍 自动检测：开始检查是否是最后一个提交的专家');
      
      // 调用检查接口
      // 评标：flag=2, supplierId=当前选中的供应商ID
      final supplierId = selectedSupplier.value?.supplierId ?? 0;
      
      final isLastExpert = await ProjectApi.checkTheLastExpert(
        projectId: projectId!,
        supplierId: supplierId, // 评标时使用当前供应商ID
        flag: 2, // 2-作为评标人
      );
      
      if (isLastExpert) {
        // 是最后一个专家，自动勾选组长
        isTeamLeader.value = true;
        debugPrint('✅ 自动检测：是最后一个专家，已自动勾选组长');
      } else {
        // 不是最后一个专家
        isTeamLeader.value = false;
        debugPrint('ℹ️ 自动检测：不是最后一个专家');
      }
      
    } catch (e) {
      debugPrint('⚠️ 自动检测组长状态失败: $e');
      isTeamLeader.value = false;
    } finally {
      isCheckingLastExpert.value = false;
    }
  }
  
  /// 处理组长勾选
  /// 用户手动点击checkbox时调用
  Future<void> onLeaderCheckboxTap() async {
    // 如果当前已经是组长状态，直接取消勾选
    if (isTeamLeader.value) {
      isTeamLeader.value = false;
      debugPrint('🔓 取消组长勾选');
      return;
    }
    
    // 如果要勾选组长，需要先检查是否是最后一个专家
    try {
      isCheckingLastExpert.value = true;
      
      debugPrint('🔍 手动检查：开始检查是否是最后一个提交的专家');
      
      // 调用检查接口
      // 评标：flag=2, supplierId=当前选中的供应商ID
      final supplierId = selectedSupplier.value?.supplierId ?? 0;
      
      final isLastExpert = await ProjectApi.checkTheLastExpert(
        projectId: projectId!,
        supplierId: supplierId, // 评标时使用当前供应商ID
        flag: 2, // 2-作为评标人
      );
      
      if (isLastExpert) {
        // 是最后一个专家，允许勾选组长
        isTeamLeader.value = true;
        debugPrint('✅ 手动检查：是最后一个专家，已勾选组长');
        
        // 显示成功提示
        EasyLoading.showToast(
          '已设置为评标组长',
          duration: const Duration(seconds: 2),
          toastPosition: EasyLoadingToastPosition.center,
          maskType: EasyLoadingMaskType.clear,
        );
      } else {
        // 不是最后一个专家，不允许勾选
        isTeamLeader.value = false;
        debugPrint('⚠️ 手动检查：不是最后一个专家，不能勾选组长');
        
        // 显示提示
        EasyLoading.showToast(
          '只有最后一位提交评标的专家才能设置为组长',
          duration: const Duration(seconds: 3),
          toastPosition: EasyLoadingToastPosition.center,
          maskType: EasyLoadingMaskType.clear,
        );
      }
      
    } catch (e) {
      debugPrint('❌ 手动检查最后专家失败: $e');
      isTeamLeader.value = false;
      
      // 显示错误提示
      EasyLoading.showToast(
        '检查组长资格失败，请稍后重试',
        duration: const Duration(seconds: 2),
        toastPosition: EasyLoadingToastPosition.center,
        maskType: EasyLoadingMaskType.clear,
      );
    } finally {
      isCheckingLastExpert.value = false;
    }
  }

  /// 隐藏供应商评标弹窗
  void hideSupplierBidBottomSheet() {
    showSupplierBidSheet.value = false;
    // 不清空选中的供应商，可能还需要用到数据
  }
  
  /// 更新评标意见
  void updateBidOpinion(String value) {
    bidOpinion.value = value;
  }
  
  /// 清除手写签名
  void onClearSignature() {
    try {
      debugPrint('🗑️ 采购评估详情页 - 清除手写签名');
      signatureController.clear();
      hasSignature.value = false;
      signatureUploaded.value = false;
    } catch (e) {
      debugPrint('❌ 采购评估详情页 - 清除签名异常: $e');
    }
  }
  
  /// 将签名转换为图片文件
  Future<File?> _convertSignatureToImageFile() async {
    try {
      debugPrint('🖼️ 采购评估详情页 - 开始转换签名为图片');
      
      if (signatureController.isEmpty) {
        debugPrint('⚠️ 签名为空，无法转换');
        return null;
      }
      
      // 获取签名的图片数据
      final Uint8List? signatureBytes = await signatureController.toPngBytes();
      if (signatureBytes == null) {
        debugPrint('❌ 签名转换失败');
        return null;
      }
      
      // 创建临时文件
      final String timestamp = DateTime.now().millisecondsSinceEpoch.toString();
      final String fileName = 'signature_bid_$timestamp.png';
      
      // 使用系统临时目录
      final String tempPath = Directory.systemTemp.path;
      final String filePath = '$tempPath/$fileName';
      
      // 写入文件
      final File signatureFile = File(filePath);
      await signatureFile.writeAsBytes(signatureBytes);
      
      debugPrint('✅ 签名转换成功: $filePath');
      debugPrint('📄 文件大小: ${signatureBytes.length} bytes');
      
      return signatureFile;
      
    } catch (e) {
      debugPrint('❌ 签名转换异常: $e');
      return null;
    }
  }
  
  /// 🎯 第一步：提交评分表格数据
  Future<void> submitScoreTable() async {
    try {
      debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      debugPrint('📊 第一步：提交评分表格 - 开始');
      debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      debugPrint('');
      
      // 打印项目和供应商信息
      debugPrint('🎯 评分目标信息：');
      debugPrint('  ├─ 项目ID (projectId): $projectId');
      debugPrint('  ├─ 项目名称: ${project.value?.projectName ?? "未知"}');
      debugPrint('  ├─ 供应商ID (supplierId): ${selectedSupplier.value?.supplierId ?? "无"}');
      debugPrint('  ├─ 供应商名称 (corpName): ${selectedSupplier.value?.corpName ?? "未知"}');
      debugPrint('  ├─ 供应商关联记录ID (id): ${selectedSupplier.value?.id}');
      debugPrint('  └─ 专家ID (expertId): $currentExpertId');
      debugPrint('');
      
      // 🔥 第一步：验证所有评分项是否都已填写
      debugPrint('🔍 开始验证评分项完整性...');
      final validationResult = _validateAllScoresFilled();
      if (!validationResult['isValid']) {
        final missingItems = validationResult['missingItems'] as List<String>;
        debugPrint('❌ 评分验证失败，以下评分项未填写：');
        for (var item in missingItems) {
          debugPrint('   ⚠️ $item');
        }
        debugPrint('');
        
        // 显示详细的错误提示
        LoadingUtil.error(
          '请完成所有评分项！\n\n未填写的评分项：\n${missingItems.take(3).join('\n')}${missingItems.length > 3 ? '\n...(还有${missingItems.length - 3}项)' : ''}',
        );
        return;
      }
      debugPrint('✅ 评分验证通过，所有评分项都已填写');
      debugPrint('');
      
      // 收集评分数据
      final scores = <String, String>{};
      scoreControllers.forEach((key, controller) {
        scores[key] = controller.text;
      });
      
      debugPrint('📝 收集到的评分数据：');
      if (scores.isEmpty) {
        debugPrint('  ⚠️ 没有收集到任何评分数据');
      } else {
        scores.forEach((key, value) {
          debugPrint('  ├─ $key: $value');
        });
      }
      debugPrint('');
      
      // 组装 tableHeader 和 tableData
      // 根据实际的评分规则结构来组装数据
      String tableHeader = '';
      String tableData = '';
      int totalScore = 0;
      
      // 解析评分规则，组装表格数据
      if (projectRules.value?.scoreRule?.isNotEmpty == true) {
        try {
          final List<dynamic> scoreRules = jsonDecode(projectRules.value!.scoreRule!);
          
          // 🔥 动态生成表头（包含单位名称列）- 根据评分规则的子项或主项
          StringBuffer tableHeaderBuffer = StringBuffer();
          tableHeaderBuffer.write('<tr>\n');
          
          // 第一列：单位名称（供应商名称）
          tableHeaderBuffer.write('    <th style="text-align: center; font-weight: bold;">单位名称</th>\n');
          
          // 动态生成评分项列
          for (var rule in scoreRules) {
            final Map<String, dynamic> ruleMap = rule as Map<String, dynamic>;
            final String type = ruleMap['type'] ?? '';
            final String content = ruleMap['content'] ?? '';
            final String score = ruleMap['score'] ?? '';
            final List<dynamic> subItems = ruleMap['subItems'] ?? [];
            
            if (type == 'total') continue; // 跳过总分行
            
            // 如果有子项，为每个子项创建列
            if (subItems.isNotEmpty) {
              for (var j = 0; j < subItems.length; j++) {
                final Map<String, dynamic> subMap = subItems[j] as Map<String, dynamic>;
                final String subContent = subMap['content'] ?? '';
                final String subScore = subMap['score'] ?? '';
                tableHeaderBuffer.write('    <th style="text-align: center; font-weight: bold;">$subContent<br/>($subScore)</th>\n');
              }
            } else {
              // 没有子项，为主项创建列
              tableHeaderBuffer.write('    <th style="text-align: center; font-weight: bold;">$content<br/>($score)</th>\n');
            }
          }
          
          // 最后一列：总分
          tableHeaderBuffer.write('    <th style="text-align: center; font-weight: bold;">总分</th>\n');
          tableHeaderBuffer.write('</tr>');
          
          tableHeader = tableHeaderBuffer.toString();
          
          // 🔥 动态生成数据行（一行数据，对应表头的各列）
          debugPrint('🔍 开始生成数据行...');
          StringBuffer dataRowBuffer = StringBuffer();
          dataRowBuffer.write('<tr>\n');
          
          // 第一列：供应商名称
          final supplierName = selectedSupplier.value?.corpName ?? '未知供应商';
          dataRowBuffer.write('    <td style="text-align: center;">$supplierName</td>\n');
          debugPrint('  列1: $supplierName（供应商名称）');
          
          int columnIndex = 1;
          for (var rule in scoreRules) {
            final Map<String, dynamic> ruleMap = rule as Map<String, dynamic>;
            final String type = ruleMap['type'] ?? '';
            final String content = ruleMap['content'] ?? '';
            final String criteria = ruleMap['criteria'] ?? '';
            final List<dynamic> subItems = ruleMap['subItems'] ?? [];
            
            if (type == 'total') {
              debugPrint('  跳过总分行');
              continue; // 跳过总分行
            }
            
            debugPrint('  处理: $criteria - $content (子项数: ${subItems.length})');
            
            // 如果有子项，为每个子项生成数据单元格
            if (subItems.isNotEmpty) {
              for (var i = 0; i < subItems.length; i++) {
                final Map<String, dynamic> subMap = subItems[i] as Map<String, dynamic>;
                final String subContent = subMap['content'] ?? '';
                
                final subScoreKey = 'sub_score_${content}_${subContent}_$i';
                final subScoreValue = scores[subScoreKey] ?? '';
                
                columnIndex++;
                debugPrint('  列$columnIndex: $subContent = $subScoreValue (key: $subScoreKey)');
                
                final parsedScore = double.tryParse(subScoreValue) ?? 0;
                totalScore += parsedScore.toInt();
                
                dataRowBuffer.write('    <td style="text-align: center;">$subScoreValue</td>\n');
              }
            } else {
              // 没有子项，为主项生成数据单元格
              final scoreKey = 'score_${content}_$criteria';
              final scoreValue = scores[scoreKey] ?? '';
              
              columnIndex++;
              debugPrint('  列$columnIndex: $content = $scoreValue (key: $scoreKey)');
              
              final parsedScore = double.tryParse(scoreValue) ?? 0;
              totalScore += parsedScore.toInt();
              
              dataRowBuffer.write('    <td style="text-align: center;">$scoreValue</td>\n');
            }
          }
          
          // 最后一列：总分
          columnIndex++;
          dataRowBuffer.write('    <td style="text-align: center; font-weight: bold;">$totalScore</td>\n');
          dataRowBuffer.write('</tr>');
          debugPrint('  列$columnIndex: 总分 = $totalScore');
          debugPrint('🔍 数据行生成完毕，总列数: $columnIndex');
          
          tableData = dataRowBuffer.toString();
          
        } catch (e) {
          debugPrint('❌ 解析评分规则失败: $e');
          throw Exception('评分规则解析失败，请重试');
        }
      } else {
        throw Exception('未找到评分规则配置');
      }
      
      // isLeader 根据第一步勾选的状态传递
      final isLeaderValue = isTeamLeader.value ? 1 : 0;
      
      debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      debugPrint('📝 准备调用 /v1/app/expertBid API');
      debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      debugPrint('  ⚙️ 请求参数：');
      debugPrint('     ├─ expertId: $currentExpertId');
      debugPrint('     ├─ supplierId: ${selectedSupplier.value?.supplierId}');
      debugPrint('     ├─ projectId: $projectId');
      debugPrint('     ├─ score (总分): $totalScore');
      debugPrint('     ├─ isLeader: $isLeaderValue ${isLeaderValue == 1 ? "(是组长，第一步已勾选)" : "(不是组长)"}');
      debugPrint('');
      debugPrint('📋 表格数据详情（表头与数据行上下对应）：');
      debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      debugPrint('');
      debugPrint('📊 表头（TableHeader）- 用于整个项目，存储一次：');
      debugPrint('   列1: 单位名称');
      debugPrint('   列2-N: 各评分项（根据评分规则动态生成）');
      debugPrint('   最后一列: 总分');
      debugPrint('');
      debugPrint('HTML格式：');
      debugPrint(tableHeader);
      debugPrint('');
      debugPrint('📝 数据行（TableData）- 每个专家给每个供应商打分时存储一行：');
      debugPrint('   列1: ${selectedSupplier.value?.corpName ?? "未知供应商"}（供应商名称）');
      debugPrint('   列2-N: 各评分项的实际得分（已验证所有项都已填写）');
      debugPrint('   最后一列: $totalScore（总分）');
      debugPrint('');
      debugPrint('HTML格式：');
      debugPrint(tableData);
      debugPrint('');
      debugPrint('✅ 表头列数与数据列数完全对应！');
      debugPrint('✅ 所有评分项都已填写并验证通过！');
      debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      debugPrint('');
      
      final success = await ProjectApi.expertBid(
        expertId: currentExpertId,
        supplierId: selectedSupplier.value?.supplierId ?? 0,
        projectId: projectId!,
        score: totalScore,
        tableHeader: tableHeader,
        tableData: tableData,
        isLeader: isLeaderValue, // 第一步就传递组长状态
      );
      
      if (success) {
        scoreSubmitted.value = true;
        debugPrint('✅ 第一步：评分表格提交成功');
        
        LoadingUtil.success('评分已提交，请继续签名');
      }
      
    } catch (e) {
      debugPrint('❌ 第一步：提交评分失败: $e');
      LoadingUtil.error(e.toString().replaceAll('Exception: ', ''));
    }
  }
  
  /// 🎯 第二步：上传签名和意见
  Future<void> uploadSignatureAndOpinion() async {
    try {
      debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      debugPrint('🖊️ 第二步：上传签名和意见 - 开始');
      debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      debugPrint('');
      
      if (!hasSignature.value || signatureController.isEmpty) {
        LoadingUtil.info('请先完成手写签名');
        return;
      }
      
      // 如果是组长，验证是否填写了意见
      if (isTeamLeader.value && bidOpinion.value.trim().isEmpty) {
        LoadingUtil.info('组长需要填写评标意见');
        return;
      }
      
      // 开始上传
      isUploading.value = true;
      uploadErrorMessage.value = '';
      
      debugPrint('🔄 采购评估详情页 - 开始转换并上传签名');
      debugPrint('');
      
      // 将签名转换为图片文件
      final signatureFile = await _convertSignatureToImageFile();
      if (signatureFile == null) {
        uploadErrorMessage.value = '签名转换失败，请重新签名';
        LoadingUtil.error('签名转换失败，请重新签名');
        return;
      }
      
      final isLeaderValue = isTeamLeader.value ? 1 : 0;
      final bidSuggestion = isTeamLeader.value ? bidOpinion.value.trim() : null;
      
      debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      debugPrint('📝 准备调用 /v1/app/uploadImg API - 评标人签名');
      debugPrint('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      debugPrint('');
      debugPrint('🎯 评标目标信息：');
      debugPrint('  ├─ 项目ID (projectId): $projectId');
      debugPrint('  ├─ 项目名称: ${project.value?.projectName ?? "未知"}');
      debugPrint('  ├─ 供应商ID (supplierId): ${selectedSupplier.value?.supplierId ?? "无"}');
      debugPrint('  ├─ 供应商名称 (corpName): ${selectedSupplier.value?.corpName ?? "未知"}');
      debugPrint('  └─ 专家ID (expertId): $currentExpertId');
      debugPrint('');
      debugPrint('⚙️ 请求参数：');
      debugPrint('  ├─ expertId: $currentExpertId');
      debugPrint('  ├─ projectId: $projectId');
      debugPrint('  ├─ flag: 2 (评标人)');
      debugPrint('  ├─ isLeader: $isLeaderValue ${isLeaderValue == 1 ? "(是组长，已在第一步提交)" : "(不是组长，已在第一步提交)"}');
      debugPrint('  ├─ bid_suggestion: ${bidSuggestion ?? "(空 - 非组长无需填写)"}');
      debugPrint('  └─ file: ${signatureFile.path}');
      debugPrint('');
      
      // 调用上传签名API（评标人）
      // flag=2 表示评标人
      final uploadResult = await ProjectApi.uploadSignature(
        expertId: currentExpertId,
        projectId: projectId!,
        flag: 2, // 2-评标人签名
        file: signatureFile,
        bidSuggestion: bidSuggestion,
        isLeader: isLeaderValue,
      );
      
      if (uploadResult.success) {
        debugPrint('✅ 采购评估详情页 - 签名和意见上传成功: ${uploadResult.url}');
        
        // 标记签名已上传成功
        signatureUploaded.value = true;
        
        // 清理临时文件
        try {
          await signatureFile.delete();
          debugPrint('🗑️ 临时签名文件已清理');
        } catch (e) {
          debugPrint('⚠️ 清理临时文件失败: $e');
        }
        
        // 🔥 优化：确保所有加载提示都已关闭
        EasyLoading.dismiss();
        debugPrint('🔄 确保所有加载框已关闭');
        
        // 稍微延迟确保加载框完全消失
        await Future.delayed(const Duration(milliseconds: 100));
        
        // 关闭弹窗
        hideSupplierBidBottomSheet();
        debugPrint('🚪 评标弹出框已关闭');
        
        // 稍微延迟确保弹窗完全关闭
        await Future.delayed(const Duration(milliseconds: 300));
        
        // 刷新供应商列表
        await refreshProjectSuppliers();
        
        // 显示成功提示
        LoadingUtil.success('评标已完成');
        
      } else {
        debugPrint('❌ 采购评估详情页 - 签名上传失败: ${uploadResult.errorMessage}');
        uploadErrorMessage.value = uploadResult.errorMessage ?? '上传失败';
        
        LoadingUtil.error(uploadResult.errorMessage ?? '签名上传失败，请重试');
      }
      
    } catch (e) {
      debugPrint('❌ 采购评估详情页 - 上传签名异常: $e');
      uploadErrorMessage.value = '网络错误，请重试';
      
      LoadingUtil.error('签名上传失败，请检查网络后重试');
    } finally {
      isUploading.value = false;
    }
  }

  void onTap() {}

  @override
  void onReady() {
    super.onReady();
    _initData();
  }
  
  @override
  void onClose() {
    // 先关闭所有可能打开的底部弹出框
    try {
      if (Get.isBottomSheetOpen == true) {
        Get.back();
        debugPrint('🚪 关闭底部弹出框');
      }
    } catch (e) {
      debugPrint('⚠️ 关闭底部弹出框失败: $e');
    }
    
    // 释放签名控制器资源
    signatureController.dispose();
    // 释放所有评分输入控制器
    for (var controller in scoreControllers.values) {
      controller.dispose();
    }
    super.onClose();
  }
}
